package com.example.demo.web.interceptor;

import com.example.demo.web.config.JwtConfig;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.SignatureException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    private final Logger logger = LoggerFactory.getLogger(TokenInterceptor.class);
    @Autowired
    private JwtConfig jwtConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true;
        }

        /** 地址过滤 */
        String uri = request.getRequestURI();
        logger.info(uri);
        if (uri.contains("/login") || uri.contains("/error")) {
            logger.info("包含/login");
            return true;
        }
        logger.info("验证token");
        /** Token 验证 */
        String token = request.getHeader(jwtConfig.getHeader());
        if (!StringUtils.hasLength(token)) {
            token = request.getParameter(jwtConfig.getHeader());
        }
        if (!StringUtils.hasLength(token)) {
        	response.setStatus(HttpServletResponse.SC_FORBIDDEN); 
            throw new SignatureException(jwtConfig.getHeader() + "不能为空");
        }

        Claims claims = null;
        try {
            claims = jwtConfig.getTokenClaim(token);
            if (claims == null || jwtConfig.isTokenExpired(claims.getExpiration())) {
            	response.setStatus(HttpServletResponse.SC_FORBIDDEN); 
                throw new SignatureException(jwtConfig.getHeader() + "失效，请重新登录。");
            }
        } catch (Exception e) {
        	response.setStatus(HttpServletResponse.SC_FORBIDDEN); 
            throw new SignatureException(jwtConfig.getHeader() + "失效，请重新登录。");
        }

        /** 设置 identityId 用户身份ID */
        request.setAttribute("identityId", claims.getSubject());
        return true;
    }
}